package com.bawei.module_publish.openlive.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_publish.R
import com.hyphenate.chat.EMMessage
import com.hyphenate.chat.EMTextMessageBody

class ChatAdapter : RecyclerView.Adapter<ChatAdapter.ChatViewHolder>() {
    private val messages = mutableListOf<EMMessage>()

    fun addMessages(newMessages: List<EMMessage>) {
        messages.addAll(newMessages)
        notifyDataSetChanged()
    }

    fun addMessage(msg: EMMessage) {
        messages.add(msg)
        notifyItemInserted(messages.size - 1)
    }

    fun clearMessages() {
        messages.clear()
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChatViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_chat_message_push, parent, false)
        return ChatViewHolder(view)
    }

    override fun onBindViewHolder(holder: ChatViewHolder, position: Int) {
        val msg = messages[position]
        holder.bind(msg)
    }

    override fun getItemCount() = messages.size

    class ChatViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val tvName: TextView = itemView.findViewById(R.id.tvName)
        private val tvContent: TextView = itemView.findViewById(R.id.tvContent)

        fun bind(msg: EMMessage) {
            val nickname = msg.getStringAttribute("nickname", msg.from)
            val content = (msg.body as? EMTextMessageBody)?.message ?: ""
            tvName.text = "$nickname:"
            tvContent.text = content
        }
    }
}